package com.shundr.auth.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.shundr.auth.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.common.util.Base64Util;
import com.shundr.auth.common.util.LImageLoader;
import com.shundr.auth.common.util.PictureUtil;
import com.shundr.auth.common.util.ProgressDialogHelper;
import com.shundr.auth.frame.constant.LConstants;
import com.shundr.auth.frame.db.model.PictureInfo;
import com.shundr.auth.frame.util.JsonUtil;
import com.shundr.auth.frame.util.LLogger;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.auth.user.http.UserRequest;
import com.shundr.auth.user.model.UserInfo;

public class UserInfoActivity extends BaseActivity implements OnClickListener {

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";

	private ImageView ivHeadPic;
	private TextView tvName;
	private TextView tvPhone;
	private TextView tvUserQuality;
	private ImageView ivAuthStatus;
	private TextView tvPersonAuth;

	private RelativeLayout mLayoutUserHead;
	private RelativeLayout mLayoutNoName;
	private RelativeLayout mLayoutNoAuth;
	private LinearLayout mLayoutUserInfo;
	private RelativeLayout mLayoutUserPhone;
	private RelativeLayout mLayoutUserQuality;
	private RelativeLayout mLayoutAddTruck;
	private RelativeLayout mLayoutComAuth;
	private ImageView ivComAuth;
	private int authStatus;
	private Uri outUri;

	private DisplayImageOptions mOptions;

	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();

	private UserInfo mUserInfo;

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case UserRequest.GET_USER_DETAIL_INFO_SUCCESSED:
					mUserInfo = (UserInfo) msg.obj;
					showUserInfo(mUserInfo);
					mLayoutUserInfo.setVisibility(View.VISIBLE);
					break;
				case UserRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();
					String description = (String) msg.obj;
					ToastHelper.toastShort(mContext, description);
					break;
				case UserRequest.COMMIT_USER_HEAD_SUCCESSED:
					ToastHelper.toastShort(mContext, "头像上传成功");
					new UserRequest(mContext, mHandler).getUserInfoByToken();

					break;
					
				case UserRequest.MAKE_USER_QUALITY_SUCCESSED:
					ToastHelper.toastShort(mContext, "用户等级更新成功！");
					new UserRequest(mContext, mHandler).getUserInfoByToken();
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			ProgressDialogHelper.dismiss();
			super.handleMessage(msg);

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_info);
		
		mLayoutUserHead = (RelativeLayout) findViewById(R.id.layout_head);
		mLayoutUserPhone = (RelativeLayout) findViewById(R.id.layout_user_phone);
		mLayoutUserInfo = (LinearLayout) findViewById(R.id.activity_user_info);
		ivHeadPic = (ImageView) findViewById(R.id.iv_user_info_portrait);
		tvName = (TextView) findViewById(R.id.tv_user_info_username);
		tvPhone = (TextView) findViewById(R.id.tv_user_info_phone);
		tvPersonAuth = (TextView) findViewById(R.id.tv_person_auth);
		tvUserQuality = (TextView) findViewById(R.id.tv_user_quality);
		ivAuthStatus = (ImageView) findViewById(R.id.tv_user_info_certification_status);
		mLayoutNoName = (RelativeLayout) findViewById(R.id.ll_add_name);
		mLayoutNoAuth = (RelativeLayout) findViewById(R.id.ll_data_to_renzheng);
		mLayoutUserQuality = (RelativeLayout) findViewById(R.id.layout_user_quality);
		mLayoutComAuth = (RelativeLayout) findViewById(R.id.ll_company_auth);
		ivComAuth = (ImageView) findViewById(R.id.iv_com_auth);
		mLayoutNoAuth.setOnClickListener(this);
		mLayoutUserHead.setOnClickListener(this);
		mLayoutUserPhone.setOnClickListener(this);
		mLayoutUserQuality.setOnClickListener(this);
		mLayoutComAuth.setOnClickListener(this);
		ivHeadPic.setOnClickListener(this);
		mLayoutAddTruck = (RelativeLayout) findViewById(R.id.ll_add_truck);
		mLayoutAddTruck.setOnClickListener(this);
		// mLayoutNoName.setOnClickListener(this);
		// mLayoutUserPhone.setOnClickListener(this);
		initOptions();
		ProgressDialogHelper.show(mContext, "正在加载中...");
	}

	@Override
	protected void onResume() {
		new UserRequest(mContext, mHandler).getUserInfoByToken();
		super.onResume();
	}

	/**
	 * 显示
	 * 
	 * @param info
	 */
	private void showUserInfo(UserInfo info) {
		if (info != null) {
			try {
				String name = info.getUserName();
				if (name != null) {
					tvName.setText(name);
				}
				String phone = info.getUserPhone();
				if (phone != null) {
					tvPhone.setText(phone);
				}
				authStatus = info.getIdValidationStatus();
				switch (authStatus) {
				case 0:
					ivAuthStatus.setImageResource(R.drawable.ic_auth_no);
					break;
				case 1:
					ivAuthStatus.setImageResource(R.drawable.ic_auth_ing);
					break;
				case 2:
					ivAuthStatus.setImageResource(R.drawable.ic_auth_ok);
					break;
				case 3:
					ivAuthStatus.setImageResource(R.drawable.ic_auth_fail);
					break;
				default:
					break;
				}
				
				// 如果是货主
				if (info.getUserType() == 1) {
					tvPersonAuth.setText("个人认证状态");
					mLayoutAddTruck.setVisibility(View.GONE);
					authStatus = info.getCompanyValidationStatus();
					switch (authStatus) {
					case 0:
						ivComAuth.setImageResource(R.drawable.ic_auth_no);
						break;
					case 1:
						ivComAuth.setImageResource(R.drawable.ic_auth_ing);
						break;
					case 2:
						ivComAuth.setImageResource(R.drawable.ic_auth_ok);
						break;
					case 3:
						ivComAuth.setImageResource(R.drawable.ic_auth_fail);
						break;
					default:
						break;
					}
				} else {
					mLayoutComAuth.setVisibility(View.GONE);
				}
				
				switch (info.getUserQualityStaff()) {
				case 0:
					tvUserQuality.setText("普通用户");
					tvUserQuality.setTextColor(mContext.getResources().getColor(R.color.orange_dark));
					break;
					
				case 1:
					tvUserQuality.setText("优质用户");
					tvUserQuality.setTextColor(mContext.getResources().getColor(R.color.blue_dark));
					break;

				default:
					break;
				}
				
				String headUrl = info.getUserHeadPic();
				ImageLoader.getInstance().displayImage(headUrl, ivHeadPic,
						mOptions);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onDestroy() {
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.iv_user_info_portrait:
			try {
				if (!StringUtil.isNull(mUserInfo.getUserHeadPic())) {
					Intent url = new Intent(mContext, PreviewActivity.class);
					url.putExtra("url", mUserInfo.getUserHeadPic());
					startActivity(url);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.layout_head:
			PictureUtil.doPickPhotoAction(this);
			break;
		 case R.id.ll_add_truck:
		 startActivity(new Intent(mContext, UserTruckListActivity.class));
		 break;
		 case R.id.ll_data_to_renzheng:
			 if (mUserInfo.getUserType() == 0) {
				 intent = new Intent(mContext, AuthDriverActivity.class);
			 } else {
				 intent = new Intent(mContext, AuthOwnnerActivity.class);
			 }
			 
		 
		 intent.putExtra("user", mUserInfo);
		 startActivityForResult(intent, 333);
		 break;
//		 case R.id.layout_user_quality:
//			 showMakeUserQualityDialog();
//		 break;
		 case R.id.ll_company_auth:
			 if (mUserInfo.getIdValidationStatus() == 0 || mUserInfo.getIdValidationStatus() == 3) {
				 ToastHelper.toastShort(mContext, "请先提交个人认证再进行企业认证！");
			 } else {
				 mContext.startActivity(new Intent(mContext,
							AuthCompanyActivity.class));// 货主企业认证
			 }
			 break;
		default:
			break;
		}
	}
	
//	private void showMakeUserQualityDialog() {
//		AlertDialog.Builder builder = new AlertDialog.Builder(mContext)
//											.setTitle("设置用户等级")
//											.setMessage("请谨慎修改用户等级！")
//											.setNegativeButton("普通用户", new DialogInterface.OnClickListener() {
//												
//												@Override
//												public void onClick(DialogInterface dialog, int which) {
//													changeUserQuality(0);
//													dialog.dismiss();
//												}
//											})
//											.setPositiveButton("优质用户", new DialogInterface.OnClickListener() {
//												
//												@Override
//												public void onClick(DialogInterface dialog, int which) {
//													changeUserQuality(1);
//													dialog.dismiss();
//													
//												}
//											});
//		builder.show();
//	}
	
//	private void changeUserQuality(int quality) {
//		if (mUserInfo.getUserQualityStaff() != quality) {
//			new UserRequest(mContext, mHandler).makeUserQuality(mUserInfo.getUserPhone(), quality);
//		}
//	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		Uri data2 = null;
		if (data == null) {
			data2 = PictureUtil.getImageUri();
		} else {
			data2 = data.getData();
		}
		String outPic = "";
		if (resultCode == RESULT_OK) {
			try {
				switch (requestCode) {
				case PictureUtil.PHOTO_PICKED_WITH_DATA:
					outUri = PictureUtil.getImageCaiUri();
				cropImage(data2, outUri);
					break;
				case PictureUtil.CAMERA_WITH_DATA:
					outPic = LConstants.TEMP_PIC_PATH;
					outUri = PictureUtil.getImageCaiUri();
					if (!new File(outPic).exists()) {
						ToastHelper.toastShort(mContext, getResources()
								.getString(R.string.image_error));
						return;
					}
					data2 = Uri.parse("file://" + outPic);
					
					cropImage(data2, outUri);
					break;
				case PictureUtil.PHOTO_CROP:
					outPic = PictureUtil.getRealFilePath(mContext, outUri);
					if (!new File(outPic).exists()) {
						ToastHelper.toastShort(mContext, getResources()
								.getString(R.string.image_error));
						return;
					}
					Bitmap bitmap1 = BitmapFactory.decodeFile(outPic);
					PictureInfo info1 = new PictureInfo();
					info1.setFileBase64Body(Base64Util.encodeImage(bitmap1));
					info1.setFilename(outPic);
					bitmap1.recycle();
					info1.setType(PictureInfo.FileType.head);
					mPictures.add(info1);
					String json1 = JsonUtil.toJson(mPictures);
					LLogger.e(json1);
					ProgressDialogHelper.show(mContext, "上传头像...");
					new UserRequest(mContext, mHandler).commitUserHead(json1);
					break;
				case 501:
					new UserRequest(mContext, mHandler).getUserInfoByToken();
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void cropImage(Uri inUri, Uri outUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(inUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("scale", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
		intent.putExtra("return-data", false);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		startActivityForResult(intent, PictureUtil.PHOTO_CROP);
	}

	private void initOptions() {
		mOptions = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.iv_head)
				// 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.iv_head).cacheInMemory(true)
				// 设置图片加载/解码过程中错误时候显示的图片
				.cacheInMemory(true)
				// 设置下载的图片是否缓存在内存中
				.cacheOnDisc(true)
				// 设置下载的图片是否缓存在SD卡中
				.considerExifParams(true)
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
				.bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
				// .decodingOptions(Options decodingOptions)//设置图片的解码配置
				.considerExifParams(true)// 设置图片下载前的延迟
				// .delayBeforeLoading(int delayInMillis)//int
				// delayInMillis为你设置的延迟时间
				// 设置图片加入缓存前，对bitmap进行设置
				// .preProcessor(BitmapProcessor preProcessor)
				// .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
				.displayer(new RoundedBitmapDisplayer(5))// 是否设置为圆角，弧度为多少
				// .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
				.build();// 构建完成
	}
}
